/**
 * 
 * Randomly generates terrain,
 * given a set of tiles it can use.
 * 
 * starts at bottom left, works towards the right
 * then resets to the left and up one
 * 
 * @author Andrew
 * @creator Andrew
 * 
 * LAST UPDATED 2/4/12 Andrew
 */
public class RandomTerrainGenerator {
	
	public TileObject[] inputTiles;
	
	public TileObject[] outputTiles;
	
	// Map is required for setting neighbours
	public Map input;
	
	public RandomTerrainGenerator(TileObject[] in) {
		this.inputTiles = in;
		// make a map out of it
		this.input = new Map(in);
		// set the neighbours
		this.input.setNeighbours(900,800);
		// and generate
		run();
		
	}
	
	private void run() { 
		int n = 0;
		// For every tile...
		for(TileObject x : input.tileList) {
			// the base chance is 0.2
			double chance = 0.2;
			
			// WARNING:
			/** 
			 * The Effect of these two tile marking checks is usually compounded.
			 * If there is an increased chance of having a tile on the right, when it comes
			 * along again and does the next line of tiles there is a higher chance of the tile above the one you
			 * just made being made, and then one next to it and so on...
			 * 
			 */
			// If it has a tile on its left...
			if(x.haveLeft()){
				// and that tile was also marked, increase the chance of being marked
				if(x.getTileLeft().getMarked()) chance += 0.55;
			}
			
			// If it has a tile on its right
			if(x.haveBottom()) {
				// and that tile was also marked, increase the chance of being marked
				if(x.getTileBottom().getMarked()) chance += 0.25;
			}
			// This is a weighting factor, favouring tiles closer to the bottom of the screen
			// WARNING THIS IS VERY SENSITIVE
			chance += (200-x.getY())/1000;
			
			// If the chance is reduced to 0 by the weighting factor, make sure there is still a small chance
			if (chance < 0.01) chance = 0.008;
			
			// if a random number is less than the chance value, the tile is marked.
			// n is a count of marked tiles
			if(Math.random() < chance) {
				x.setMarked(true);
				n++;
			}
		}
		// make a new list of tiles equal to the amount of marked tiles
		TileObject[] output = new TileObject[n];
		int p = 0;
		for(TileObject x : inputTiles) {
			// Put the marked tiles into the new array and reset their neighbour values (necessary to draw tiles correctly)
			if(x.getMarked()) {
				output[p] = x;
				p++;
				x.reset();
			}
		}
		this.outputTiles = output;
		
	}
	
	// and how to get the output
	public TileObject[] getOutput() {
		return this.outputTiles;
	}
	
	
	

}
